﻿using System;
using Microsoft.Xna.Framework;

namespace ThreeDContentPipeline
{
    public class MD2Importer : ContentImporter<KeyFrameMeshContent>
    {
        public override KeyFrameMeshContent Import(string file, ContentImporterContext context)
        {
            KeyFrameMeshContent keyFrameMesh = new KeyFrameMeshContent();
            XmlImporter importer = new XmlImporter();
            MD2File contentFile = new MD2File(file);
            Vector2 d = new Vector2(contentFile.Header.SkinWidth, contentFile.Header.SkinHeight);
            Matrix transform = Matrix.CreateRotationX(-MathHelper.PiOver2);

            for (int i = 0; i != contentFile.Header.NumTris; i++)
            {
                for (int j = 0; j != 3; j++)
                {
                    MD2TexCoord texCoord = contentFile.TexCoords[contentFile.Triangles[i].T[j]];

                    keyFrameMesh.TextureCoordinates.Add(new Vector2(texCoord.S, texCoord.T) / d);
                    keyFrameMesh.Indices.Add((short)contentFile.Triangles[i].V[j]);
                }
            }

            foreach (MD2Frame frame in contentFile.Frames)
            {
                KeyFrameContent keyFrame = new KeyFrameContent();

                for (int j = 0; j != contentFile.Header.NumXYZ; j++)
                {
                    Vector3 position = new Vector3(frame.Vertices[j].V[0], frame.Vertices[j].V[1], frame.Vertices[j].V[2]);

                    keyFrame.Positions.Add(Vector3.Transform(position * frame.Scale + frame.Translate, transform));
                }
                keyFrameMesh.KeyFrames.Add(keyFrame);
            }
            return keyFrameMesh;
        }
    }
}
